package com.zhong.gang.app.ui.zhuchang.changsure;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.luck.picture.lib.tools.ToastUtils;
import com.zhong.gang.app.R;
import com.zhong.gang.app.api.Api;
import com.zhong.gang.app.api.HttpUtils;
import com.zhong.gang.app.databinding.ActivityFaHuoChangBinding;
import com.zhong.gang.app.db.UserUtils;
import com.zhong.gang.app.ui.contract.ContractAct;
import com.zhong.gang.app.ui.contract.ContractBean;
import com.zhong.gang.app.mvp.CommonPresenter;
import com.zhong.gang.app.ui.main.MainActivity;
import com.zhong.gang.app.ui.zhuchang.changsure.modle.FaHuoChangBean;
import com.zhong.gang.app.ui.zhuchang.changsure.modle.OrderExternal;
import com.zhong.gang.app.ui.zhuchang.changsure.modle.OrderSendBean;
import com.zhong.gang.app.ui.zhuchang.changsure.modle.OrderTransfer;
import com.zhong.gang.app.utils.ShouFaView;
import com.zhong.gang.applib.bean.MaterialBean;
import com.zhong.gang.applib.config.Config;
import com.zhong.gang.applib.controller.ImgController;
import com.zhong.gang.applib.http.BaseDataBean;
import com.zhong.gang.applib.http.callback.DataCallBack;
import com.zhong.gang.applib.rx.RxManager;
import com.zhong.gang.applib.ui.ZhangKouView;
import com.zhong.gang.applib.ui.adapter.AddImgAdapter;
import com.zhong.gang.applib.utils.NumberUtils;
import com.zhong.gang.applib.utils.TimeUtils;

import java.io.File;
import java.util.Locale;

import static android.app.Activity.RESULT_OK;

public class SureOrderPersenter
        implements TextWatcher, ShouFaView.MonenyChangedListener, ZhangKouView.ZhangKouListener {
    private FaHuoChangAct activity;
    private ActivityFaHuoChangBinding binding;
    private AddImgAdapter imgAdapter, zjAdapter, bdAdapter;
    private ImgController imgController;
    private int type;
    private int orderId;
    private ContractBean.ContractMaterialTypesBean contractMaterialTypesBean;

    public SureOrderPersenter(FaHuoChangAct activity, int orderId) {
        this.activity = activity;
        this.orderId = orderId;
        binding = activity.bind;
        binding.setController(this);
        imgController = new ImgController();
        imgAdapter = imgController.initImgAdapter(activity, binding.imgRecyclerView, 0);
        zjAdapter =
                imgController.initImgAdapter(activity, binding.zjRecyclerView, Config.ZJ_NUMBER);
        bdAdapter =
                imgController.initImgAdapter(activity, binding.bgRecyclerView, Config.BD_NUMBER);

        binding.shoufaLayout.setText(binding.delete);
        binding.mWeight.addTextChangedListener(this);
        binding.pWeight.addTextChangedListener(this);
        binding.kouWeight.addTextChangedListener(this);
    }

    public void getDetail(int id) {
        HttpUtils.get(Api.confirmDetail, activity)
                 .addParams("orderId", id + "")
                 .build().execute(activity.new ActCallBack<BaseDataBean<FaHuoChangBean>>() {
            @Override
            public void onResponse(BaseDataBean<FaHuoChangBean> data) throws Exception {
                super.onResponse(data);
                if (data.getResult() == null)
                    return;
                type = data.getResult().getType();
                if (data.getResult().getType() == 0) {
                    setOrderCarMsg(data.getResult().getOrderSend());
                    binding.shoufaLayout.setShow(false);
                    binding.zhangkou.setVisibility(View.GONE);
                    binding.jMoneyLayout.setVisibility(View.GONE);
                } else if (data.getResult().getType() == 1) {
                    setExternalCarMsg(data.getResult().getOrderExternal());
                } else if (data.getResult().getType() == 2) {
                    setOrderTransfer(data.getResult().getOrderTransfer());
                    binding.shoufaLayout.setShow(false);
                    binding.zhangkou.setVisibility(View.GONE);
                    binding.jMoneyLayout.setVisibility(View.GONE);
                }
                setCanAction(data.getResult());
            }
        });
    }

    /**
     * 料场发货
     */
    private void setOrderCarMsg(OrderSendBean data) {
        if (data != null) {
            if (data.getOrderSendDispatchingCar() != null) {
                binding.carNum.setText("" + data.getOrderSendDispatchingCar().getCarNum());
                binding.startTime.setText(
                        "" + TimeUtils.getTime2(data.getOrderSendDispatchingCar().getCreateTime()));
                binding.startAddress.setText(data.getOrderSendDispatchingCar().getStartLocal());
                binding.endAddress.setText(data.getOrderSendDispatchingCar().getEndLocal());
            }
            binding.xcMWeightLayout.setVisibility(View.GONE);
            binding.xcPWeightLayout.setVisibility(View.GONE);
            binding.xcKWeightLayout.setVisibility(View.GONE);
            binding.xcKWeightLayout.setVisibility(View.GONE);
            binding.xcJWeightLayout.setVisibility(View.GONE);
            binding.zhangkouLayout.setVisibility(View.GONE);
            binding.payWayLayout.setVisibility(View.GONE);

            binding.finalMoneyLayout.setVisibility(View.GONE);
            binding.liaoTypeLayout.setVisibility(View.VISIBLE);
            binding.sn.setText("" + data.getSn());
            binding.liaoType.setText(data.getSteelMillMaterialTypeStr());
            binding.zkMoney.setText(data.getNetWeight() + "吨");
            imgController.addImgView(imgAdapter, data.getPersonCarPhoto());
            imgController.addImgView(imgAdapter, data.getFullPhoto());
            binding.material.setData(data.getOrderMaterialTypeDetailList());
        }
    }

    /**
     * 外调货业
     */
    public void setExternalCarMsg(OrderExternal data) {
        if (data != null) {
            binding.zhangkouLayout.setVisibility(View.VISIBLE);
            binding.finalMoneyLayout.setVisibility(View.VISIBLE);
            binding.carNum.setText("" + data.getCarNum());
            binding.startTime.setText("" + TimeUtils.getTime2(data.getCreateTime()));
            binding.sn.setText("" + data.getSn());
            binding.liaoTypeLayout.setVisibility(View.GONE);

            binding.payWay.setText(data.getPayType() == 0 ? "打款放车" : "钢厂结算");
            binding.xcMWeight.setText(NumberUtils.getNumber(data.getStartLocalGrossWeight()) + "吨");
            binding.xcPWeight.setText(NumberUtils.getNumber(data.getStartLocalTareWeight()) + "吨");
            binding.xcKWeight.setText(NumberUtils.getNumber(data.getStartLocalSlagWeight()) + "吨");
            binding.xcJWeight.setText(NumberUtils.getNumber(data.getStartLocalFinalWeight()) + "吨");
            binding.xcKWeightLayout.setVisibility(
                    data.getPayType() == 0 ? View.VISIBLE : View.GONE);
            binding.zhangkouLayout.setVisibility(data.getPayType() == 0 ? View.VISIBLE : View.GONE);
            binding.finalMoneyLayout.setVisibility(
                    data.getPayType() == 0 ? View.VISIBLE : View.GONE);
            binding.shoufaLayout.setShow(false);
            binding.zhangkou.setVisibility(View.GONE);
            binding.jMoneyLayout.setVisibility(View.GONE);

            binding.startAddress.setText(data.getStartLocal());
            binding.endAddress.setText(data.getEndLocal());
            binding.zkMoney.setText(NumberUtils.getNumber(data.getFloatAmount() == 0 ? 0 :
                    ((data.getFloatType() == 1 ? 1 : -1) * data.getFloatAmount())) + "元");
            binding.finalMoney.setText(
                    NumberUtils.getNumber(data.getStartLocalFinalAmount()) + "元");

            imgController.addImgView(imgAdapter, data.getCarPhoto());
            imgController.addImgView(imgAdapter, data.getMaterialTypePhoto());
            binding.material.setData(data.getOrderMaterialTypeDetailList(), data.getPayType() == 0);
        }
    }

    /**
     * 中转
     *
     * @param orderTransfer
     */
    public void setOrderTransfer(OrderTransfer orderTransfer) {
        if (orderTransfer == null)
            return;
        binding.cardTitle.setText("船号");
        binding.carNum.setText(orderTransfer.getBch());
        binding.startTimeTitle.setText("创建时间");
        binding.startTime.setText(orderTransfer.getCreateTime());

        binding.xcMWeightLayout.setVisibility(View.GONE);
        binding.xcPWeightLayout.setVisibility(View.GONE);
        binding.xcKWeightLayout.setVisibility(View.GONE);
        binding.xcKWeightLayout.setVisibility(View.GONE);
        binding.xcJWeightLayout.setVisibility(View.GONE);
        binding.payWayLayout.setVisibility(View.GONE);

        binding.startAddressLayout.setVisibility(View.GONE);
        binding.zhangkouLayout.setVisibility(View.GONE);
        binding.finalMoneyLayout.setVisibility(View.GONE);
        binding.sn.setText(orderTransfer.getSn());
        if (orderTransfer.getSteelMillMaterialType() != null)
            binding.liaoType.setText(orderTransfer.getSteelMillMaterialType().getName());
        if (orderTransfer.getSteelMill() != null)
            binding.endAddress.setText(orderTransfer.getSteelMill().getName());
        binding.material.setData(orderTransfer.getMaterialTypeDetailList());
        imgController.addImgView(imgAdapter, orderTransfer.getFullPhoto());
        imgController.addImgView(imgAdapter, orderTransfer.getFalfPhoto());
    }

    /**
     * 设置点击事件
     */
    private void setCanAction(FaHuoChangBean bean) {
        boolean isAction = !bean.isDone();
        binding.sure.setVisibility(isAction ? View.VISIBLE : View.GONE);
        binding.contractLayout.setEnabled(isAction);
        binding.mWeight.setEnabled(isAction);
        binding.pWeight.setEnabled(isAction);
        binding.kouWeight.setEnabled(isAction);
        binding.buttonSwitch.setEnabled(isAction);
        if (isAction) {
            imgController.setNeedImg(zjAdapter, activity, true, Config.ZJ_NUMBER, true);
            imgController.setNeedImg(bdAdapter, activity, true, Config.BD_NUMBER, true);
            imgController.addImgView(zjAdapter, "", true);
            imgController.addImgView(bdAdapter, "", true);
        }
        if (isAction) {
            binding.shoufaLayout.setListener(this);
            binding.zhangkou.setListener(this);
            binding.shoufaLayout.setData(UserUtils.getIntent(activity).getUser().getSteelMillId(),
                    1, 0.0);
            binding.zhangkou.setAction(true);
            binding.zhangkou.setEnabled(true);
            binding.zhangkou.setCheckStatus(false);
        } else {
            setContract(bean);
            binding.zhangkou.setAction(false);
            binding.zhangkou.getBinding().zhangkouType.setText(
                    bean.getFloatType() == 1 ? "涨" : "扣");
            binding.zhangkou.getBinding().monenyEdt.setText(
                    NumberUtils.getNumber(bean.getFloatAmount()) + "");
            binding.zhangkou.setEnabled(false);
            binding.jMoney.setText(bean.getSteelMillFinalAmount() + "");
            binding.zhangkou.setCheckStatus(bean.getFloatAmount() != 0);
            for (MaterialBean data : bean.getOrderMaterialTypeDetailList()) {
                binding.shoufaLayout.addView(data);
            }
            binding.delete.setVisibility(View.GONE);
        }
    }

    /**
     * 放入合同内容
     */
    private void setContract(FaHuoChangBean bean) {
        binding.mWeight.setText(bean.getSteelMillGrossWeight() + "");
        binding.pWeight.setText(bean.getSteelMillTareWeight() + "");
        binding.jWeight.setText(bean.getSteelMillNetWeight() + "");
        binding.jsWeight.setText(
                String.format(Locale.CHINA, "%.2f", (float) bean.getSteelMillFinalWeight()));
        binding.buttonSwitch.setChecked(!TextUtils.isEmpty(bean.getSteelMillQualityPhoto()));
        binding.kouWeight.setText(bean.getSteelMillSlagWeight() + "");
        imgController.addImgView(zjAdapter, bean.getSteelMillQualityPhoto());
        imgController.addImgView(bdAdapter, bean.getSteelMillPoundPhoto());
        FaHuoChangBean.ContractBean contractBean = bean.getContract();
        if (contractBean == null) {
            return;
        }
        binding.contractTv.setText(contractBean.getSn());
    }

    /**
     * 点击事件
     */
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.contract_layout:
                activity.startActivityForResult(new Intent(activity, ContractAct.class),
                        Config.CONTRACT_NUMBER);
                break;
            case R.id.sure://保存
                double mWeight = getDouble(binding.mWeight);
                double pWeight = getDouble(binding.pWeight);
                double kWeight = getDouble(binding.kouWeight);
                int switchStatus = binding.buttonSwitch.isChecked() ? 1 : 0;
                String list = binding.shoufaLayout.getJsonArray();
                if (TextUtils.isEmpty(list)) {
                    ToastUtils.s(activity, "请填写完整料型信息");
                    return;
                }
                File zjFile = imgController.getFile(zjAdapter);
                File bdFile = imgController.getFile(bdAdapter);
                if (binding.buttonSwitch.isChecked()) {
                    if (zjFile == null) {
                        ToastUtils.s(activity, "请上传质检照片");
                        return;
                    }
                }
                if (bdFile == null) {
                    ToastUtils.s(activity, "请上传榜单照片");
                    return;
                }
                if (binding.buttonSwitch.isChecked())
                    upZjPhoto(zjFile, bdFile, mWeight, pWeight, switchStatus, kWeight, list,
                            binding.zhangkou.getMoneny());
                else
                    upBdPhoto("", bdFile, mWeight, pWeight, switchStatus, kWeight, list,
                            binding.zhangkou.getMoneny());
                break;
        }
    }


    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != RESULT_OK || data == null)
            return;
        else if (requestCode == Config.CONTRACT_NUMBER) {
            ContractBean.ContractMaterialTypesBean bean =
                    (ContractBean.ContractMaterialTypesBean) data.getSerializableExtra(
                            Config.CONTRACT);
            contractMaterialTypesBean = bean;
            binding.contractTv.setText(bean.getContractSn());
            return;
        }
        imgController.onActivityResult(requestCode == Config.ZJ_NUMBER ? zjAdapter : bdAdapter,
                resultCode, data);
    }

    /**
     * 获取double
     */
    public double getDouble(TextView textView) {
        double number = 0.0;
        try {
            number = Double.parseDouble(textView.getText().toString());
        } catch (Exception e) {
        }
        return NumberUtils.getNumber(number);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        double mWeight = getDouble(binding.mWeight);
        double pWeight = getDouble(binding.pWeight);
        double jWeight = mWeight - pWeight;
        jWeight = jWeight < 0 ? 0 : jWeight;
        binding.jWeight.setText(String.format(Locale.CHINA, "%.2f", (float) jWeight));
        double kWeight = getDouble(binding.kouWeight);
        double jsWeight = jWeight - kWeight;
        jsWeight = jsWeight < 0 ? 0 : jsWeight;
        binding.jsWeight.setText(String.format(Locale.CHINA, "%.2f", (float) jsWeight));
        binding.shoufaLayout.setAllWeight(jsWeight);
    }

    /**
     * 上传质检图片
     */
    private void upZjPhoto(File zjFile, File bdFile, double mWeight, double pWeight,
            int switchStatus, double kWeight, String list, double floatAmount) {
        CommonPresenter.upImg(activity, zjFile, new DataCallBack<BaseDataBean<String>>(activity) {
            @Override
            public void onResponse(BaseDataBean<String> data) throws Exception {
                super.onResponse(data);
                upBdPhoto(data.getResult(), bdFile, mWeight, pWeight, switchStatus, kWeight, list,
                        floatAmount);
            }
        });
    }

    /**
     * 上传榜单图片
     */
    private void upBdPhoto(String zjStr, File bdFile, double mWeight, double pWeight,
            int switchStatus, double kWeight, String list, double floatAmount) {
        CommonPresenter.upImg(activity, bdFile, new DataCallBack<BaseDataBean<String>>(activity) {
            @Override
            public void onResponse(BaseDataBean<String> data) throws Exception {
                super.onResponse(data);
                upData(zjStr, data.getResult(), mWeight, pWeight, switchStatus, kWeight, list,
                        floatAmount);
            }
        });
    }

    public void upData(String zjStr, String bdStr, double mWeight, double pWeight, int switchStatus,
            double kWeight, String list, double floatAmount) {
        String url = "";
        if (type == 0)
            url = Api.confirmToFactory;
        else if (type == 1)
            url = Api.externalConfirmToFactory;
        else
            url = Api.confirmToTransfer;
        HttpUtils.post(url, activity)
                 .addParams("orderId", orderId + "")
                 .addParams("contractId", contractMaterialTypesBean == null ? null :
                         (contractMaterialTypesBean.getId() + ""))
                 .addParams("steelMillGrossWeight", mWeight + "")
                 .addParams("steelMillTareWeight", pWeight + "")
                 .addParams("qualityCheckResult", switchStatus + "")
                 .addParams("steelMillSlagWeight", kWeight + "")
                 .addParams("steelMillQualityPhoto", zjStr)
                 .addParams("steelMillPoundPhoto", bdStr)
                 .addParams("materialTypeList", list)
                 .addParams("floatType", (floatAmount <= 0 ? 2 : 1) + "")//涨扣类型:1涨，2扣
                 .addParams("floatAmount", Math.abs(floatAmount) + "")
                 .build()
                 .execute(activity, "上传信息", new DataCallBack<BaseDataBean<String>>(activity) {
                     @Override
                     public void onResponse(BaseDataBean<String> data) throws Exception {
                         super.onResponse(data);
                         new RxManager().post(MainActivity.MAIN_ADD_OK);
                         activity.closeActivity();
                     }
                 });
    }

    @Override
    public void afterMonenyChanged(double allMoneny) {
        binding.zhangkou.setMoneny(allMoneny);
    }

    @Override
    public void onZhangKou(double money) {
        binding.jMoney.setText(money + "");
    }
}